<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <!--    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vant@2.2/lib/index.css">-->
    <!--    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>-->
    <!--    <script src="https://cdn.jsdelivr.net/npm/vant@2.2/lib/vant.min.js"></script>-->
    <!--    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>-->
    <!--    <script src="https://cdn.bootcss.com/qs/6.8.0/qs.js"></script>-->
    <!--    <script src="https://cdn.bootcss.com/echarts/4.2.1-rc1/echarts.min.js"></script>-->

    <link rel="stylesheet" href="./vander/vant.css">
    <script src="./vander/vue.min.js"></script>
    <script src="./vander/vant.lib.min.js"></script>
    <script src="./vander/axios.min.js"></script>
    <script src="./vander/qs.js"></script>
    <script src="./vander/echarts.js"></script>
    <title>量表</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            overflow: hidden;
        }

        #app {
            height: 100vh;
            margin-top: 20px;
        }

        .panel {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .nav {

        }


        .cntWarp {
            padding: 5px 20px 20px 20px;
            display: flex;
            flex: 1;
            flex-direction: column;

            overflow: scroll;
        }

        p {
            margin: 0;
            font-size: 17px;
            text-align: center;
            margin-bottom: 30px;
        }

        .van-button {
            margin-top: 30px;
            height: 38px;
            line-height: 36px;
        }

        .questionnaire p {
            margin: 5px 0;
            text-align: left;
            font-size: 15px;
            font-weight: 600;
        }

        .van-radio, .van-checkbox {
            margin: 6px 0;
        }

        .van-radio__label, .van-checkbox__label {
            font-size: 15px;
        }

        .van-radio input, .van-checkbox input {
            border: 0;
            outline: 0;
            border-bottom: 1px solid #ddd;
        }

        .subTitle {
            margin-top: 22px !important;
            font-size: 18px !important;
        }

        .groupTitle {
            margin-top: 10px !important;
        }

        .title {
            display: flex;
            align-items: start;
        }

        .requireImg {
            display: inline-block;
            width: 9px;
            height: 9px;
            margin-right: 5px;
            margin-top: 11px;
        }

        .topic {
            font-size: 15px;
            color: #999999;
        }

        .fromTitle {
            font-size: 16px;
            text-align: center;
            margin: 10px 0;
            margin-bottom: 20px;
            /*color: #4CA8E8*/
        }


        #eChart {
            width: 100%;
            height: 420px
        }

        .ab-title {
            display: inline-block;
            margin-top: 25px;
            font-size: 16px;
            font-weight: bold;
            color: #333;
        }

        .about .item {
            margin-bottom: 10px;
        }

        .about .itemTitle {
            font-size: 15px;
            font-weight: 500;
            color: #333;
        }

        .about .content {
            font-size: 15px;
            color: #717171;
        }

        .card {
            padding: 20px 20px 10px 20px;
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 8px 12px #ebedf0;
        }

        table {
            margin-top: 5px;
        }

        table th {
            width: 25%;
            background: rgba(59, 143, 255, 0.47);
            text-align: center;
            font-size: 15px;
            font-weight: normal;
            min-height: 40px;
        }

        table tr {
            width: 25%;
            background: rgba(59, 143, 255, 0.15);
            text-align: center;
            font-size: 15px;
            font-weight: normal;
            min-height: 40px;
            height: 40px;
        }

        .inputTxt {
            border: none;
            border-bottom: 1px solid #ebedf0;
            font-size: 14px;
            padding: 0 0;
            width: 50%;
        }

        input::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
            color: rgba(69, 90, 100, 0.6);
            font-size: 14px;
            font-weight: 300;
        }

    </style>
</head>


<body>
<div id="app">
    <div class="panel">
        <div class="nav">
            <!--            :right-text="pageType == 1 ? '历史答题':''"-->
            <van-nav-bar
                    :title="getNavTitle"
                    :style="{height: navHeight + 'px',lineHeight: navHeight + 'px'}"
                    left-text="返回"
                    :right-text="''"
                    left-arrow
                    @click-left="onClickLeft"
                    @click-right="onClickRight"
            />
        </div>
        <div class="cntWarp">
            <transition name="van-slide-up">
                <!--        答题界面-->
                <div v-if="pageType == 1" class="questionnaire">
                    <questions :list="questionnaireList"></questions>
                    <van-button type="primary" size="large" @click="ok">提交</van-button>
                    <div style="margin-top: 20px;color: #7d7e80"> 参考文献： </div>
                    <div style="margin: 10px 0;color: #7d7e80;word-wrap:break-word"> {{reference}} </div>
                </div>
                <!--        答题历史列表-->
                <div v-if="pageType == 2" class="historyList">
                    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
                        <van-list
                                v-model="loading"
                                :finished="finished"
                                finished-text="没有更多了"
                                @load="onLoad"
                        >
                            <van-cell v-for="(item, index) in hisList" :key="item"
                                      :title="item.check_code + '（' +item.check_name + '）'"
                                      :value="dateFormat('YYYY-mm-dd', new Date(item.create_date))"
                                      @click="cellClick(item)">
                            </van-cell>
                        </van-list>
                    </van-pull-refresh>
                </div>

                <!--            结果报告-->
                <div v-if="pageType == 3" class="report">
                    <div>
                        <div id="eChart"/>
                    </div>
                    <div class="about">
                        <span class="ab-title">健康介绍</span>
                        <div class="card">
                            <div v-for="(n ,key) in aboutData" :key="key" class="item">
                                <span class="itemTitle">{{n.check_name + '：'}}</span>
                                <span class="content">{{n.check_desc + '。'}}</span>
                            </div>
                        </div>
                        <div class="table">
                            <span class="ab-title">问卷对照表</span>
                            <table>
                                <tr>
                                    <th>危险因素</th>
                                    <th>{{'本次（' + create_date + '）'}}</th>
                                    <th>{{'上次（' + lastDate + '）'}}</th>
                                    <th>变化情况</th>
                                </tr>
                                <tr v-for="(n, key) in tableData" :key="key">
                                    <td>{{n.check_name}}</td>
                                    <td>{{n.current_check_value}}</td>
                                    <td>{{n.last_check_value}}</td>
                                    <td>{{n.current_check_value > n.last_check_value ? '↑':'↓'}}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </transition>

        </div>
    </div>
</div>
</body>
<script>

    Vue.component('questions', {
        template: `
            <div v-for="(group, i) in list" :key="i">
                <h1 v-if="group.level === 1"
                    class="fromTitle">{{group.form_group + '（' + group.form_group_name + '）'}}</h1>


                <p class="subTitle"
                   v-if="group.form_head != 'null' && group.form_head != null ">{{group.form_head + "："}}</p>
                <p v-if="group.form_group_name != group.form_name" class="groupTitle" v-text="">
                    {{getGrupTitle(group)}}
                </p>

                <div v-if="" v-for="(n, i) in group.children" :key="i">
                    <div v-if="n.type === 'checkbox'">
                        <div class="title">
                            <img class="requireImg"
                                 src=""/>
                            <p v-text="">
                                {{getTitle(n, "【多选题】")}}
                            </p>
                        </div>
                        <van-checkbox-group v-model="n.question">
                            <van-checkbox :name="e" v-for="(e, index) in n.form_items" :key="index">
                                {{e.item_name}}
                                <input v-if="e.item_name === '其他'" v-model="e.inputValue" type="text">
                            </van-checkbox>
                        </van-checkbox-group>
                    </div>
                    <div v-else-if="n.type === 'radio'">
                        <div class="title">
                            <img class="requireImg"
                                 src=""/>
                            <p v-text="">
                                {{getTitle(n, "【单选题】")}}
                            </p>
                        </div>
                        <van-radio-group v-model="n.question">
                            <van-radio :name="e" v-for="(e, index) in n.form_items" :key="index">
                                {{e.item_name}}
                                <input v-if="e.item_name === '其他'" v-model="e.inputValue" type="text">
                            </van-radio>
                        </van-radio-group>
                    </div>
                    <div v-else-if="n.type === 'text'">
                        <div class="title">
                            <img class="requireImg"
                                 src=""/>
                            <p v-text=""> {{getTitle(n, "")}} </p>
                        </div>
                        <van-field v-model="n.question" type="number" class="inputTxt" :placeholder="n.default_value"/>

                    </div>
                    <questions v-if="n.children.length != 0" :list="[n]"></questions>
                </div>

            </div>
        `,
        props: ['list'],
        computed: {
            getGrupTitle() {
                return function (group) {
                    if (group.level === 1) {
                        return group.form_name
                    } else {
                        return group.index + '、' + group.form_name
                    }
                }
            },
            getTitle() {
                return function (n, type) {
                    if (n.level == 2) {
                        return n.index + '、' + n.form_name + type
                    } else {
                        return '(' + n.index + ')' + '、' + n.form_name + type
                    }
                }
            },
        }
    });

    new Vue({
        el: '#app',
        computed: {
            getNavTitle() {
                if (this.pageType == 1) {
                    return this.questionType + '问卷'
                } else if (this.pageType == 2) {
                    return '历史问卷'
                } else if (this.pageType == 3) {
                    return this.questionType + '问卷详请'
                }
            }
        },
        data() {
            return {
                result: [],
                radio: '',
                form: {
                    name: '',
                    hospital_name: '',
                    mobile: '',
                    email: ''
                },
                questionnaireList: [],
                childrenResults: [],


                pageType: this.getQueryVariable('pagetype') == false ? 1 : this.getQueryVariable('pagetype'),
                questionType: this.getQueryVariable('questiontype'),
                create_date: this.getQueryVariable('create_date'),
                reference: this.getQueryVariable('reference'),
                id: this.getQueryVariable('id'),
                orgLocal: this.getQueryVariable('orglocal'),
                // navHeight: pensionPlatform.getTitleHeight(),
                // token: pensionPlatform.getToken(),
                // requestUrl: pensionPlatform.getBaseUrl(),

                // navHeight: null,
                // token: null,
                // requestUrl: null,
               
                navHeight: this.getQueryVariable('height'),
                token: 'Bearer ' + this.getQueryVariable('token'),
                requestUrl: this.getQueryVariable('url'),

                // navHeight: 46,
                // token: 'Bearer eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxMzcwNzMxMDAwMSIsImNyZWF0ZWQiOjE2MDAzNDAwNDc4NjAsInNvdXJjZSI6NCwiZXhwIjoxNjAwOTQ0ODQ3LCJwbGF0Zm9ybSI6IndlYiIsInVzaWQiOiJhM2ZiYjUzYjQ0MmM0ZmU0OTQzYjMxMGU2OTdjNWNhNSIsInVzZXJuYW1lIjoiMTM3MDczMTAwMDEifQ.jO9HVd0PntBY5pfnBTZ4ve0NJg0rpHC7kFBB34YEoSDAFwqVlYvIllMCeNaxTwC4O6hTnYUdTokJh1S0vCQROo0w4ccCVglV_NyQ1Y6R7fXsg3RRVWYJph6xMEng4_xG9uRZHtpxNNrkf9pek-GJBT0QjbwdLLJzenCmkUrH2uc',
                // requestUrl: 'https://www.honglutec.com/oldman',
                // requestUrl: 'http://localhost:9000',
                // requestUrl: 'https://www.honglutec.com/oldman',


                pageSize: 10, // 每页条数
                pageIndex: 1, // 页码
                hisList: [],
                loading: false,   //是否处于加载状态
                finished: false,  //是否已加载完所有数据
                refreshing: false,   //是否处于下拉刷新状态

                lineChart: null,
                lastDate: '-',
                aboutData: [],
                tableData: [],
            }
        },
        created() {

        },
        mounted() {
          // this.nativeData();

            if (this.pageType == 1) {
                this.init()
                this.reference =  decodeURIComponent(this.reference)

            } else if (this.pageType == 3) {
                this.loadHistoryFormData()
            }
        },
        methods: {

            nativeData () {
                console.log("=====>  vv")

                window.webkit.messageHandlers.NativeData.postMessage(null);
            },
            setNativeData( token, baseUrl) {
                console.log("=====>  ", token)
                this.navHeight = topHeight;
                this.token = token;
                this.requestUrl = baseUrl;
            },

            init: function () {
                var _this = this
                _this.$toast.loading({
                    message: '加载中...',
                    forbidClick: true
                });
                axios.post(_this.requestUrl + '/dyicform/create', {form_group: _this.questionType}, {
                    headers: {
                        Authorization: _this.token
                    }
                }).then(function (response) {
                    _this.$toast.clear();
                    var arr = response.data.data;
                    _this.dealAddQuestion(arr, 1);
                    _this.questionnaireList = JSON.parse(JSON.stringify(arr)); // deep copy
                })
            },
            dealAddQuestion(list, level, parentIdx) {
                var _this = this
                list.map((v, i) => {
                    if (v.children.length == 0) {
                        v.question = [];
                        v.parentIdx = parentIdx
                    }
                    v.level = level
                    v.index = i + 1

                    // v.form_items.map(item => {
                    //     item.inputValue = '';
                    //     return item
                    // })
                    _this.dealAddQuestion(v.children, level + 1, v.index);
                    return v
                })
            },
            dealData(list) {
                var _this = this
                for (let i = 0; i < list.length; i++) {
                    var item = list[i]
                    if (item.children.length === 0) {
                        if (item.type === 'radio') {
                            if (!Array.isArray(item.question)) {
                                item.question = [item.question];
                            }
                        }
                        if (item.type === 'text') {
                            if (!Array.isArray(item.question)) {
                                item.question = [{
                                    item_id: '1',
                                    item_name: item.question,
                                    item_value: item.question
                                }];
                            }
                        }

                        if (item.question.length === 0) {
                            return
                        }
                        item.question.map(v => {
                            _this.childrenResults.push({
                                form_id: item.form_id,
                                totalScore: v.item_value,
                                form_field: item.form_field,
                                type: item.type,
                                form_name: item.form_name
                            })
                        })
                    }
                    _this.dealData(item.children);
                }
            },
            checkRes(data, index) {
                for (let i = 0; i < data.length; i++) {
                    if (data[i].children && data[i].children.length) {
                        const text = this.checkRes(data[i].children, i + 1)
                        if (text) {
                            return text
                        }
                    } else {
                        if (Array.isArray(data[i].question)) {
                            if (index) {
                                return `${index}大题,第${i + 1}题未作答！`
                            } else {
                                return `第${i + 1}题未作答！`
                            }
                        }
                    }
                }
            },
            ok: function () {

                var _this = this
                var resArr = JSON.parse(JSON.stringify(_this.questionnaireList)); // deep copy
                _this.childrenResults = [];
                const text = _this.checkRes(resArr[0].children);
                if (text) {
                    _this.$notify({type: 'warning', message: text});
                    return
                }

                _this.dealData(resArr)

                var form = resArr[0];
                var saveFrom = {
                    form_id: form.form_id,
                    form_field: 'score',
                    form_group_name: form.form_group_name,
                    form_name: form.form_name,
                    form_group: form.form_group,
                    children: _this.childrenResults
                }
                _this.$toast.loading({
                    message: '提交中...',
                    forbidClick: true
                });
                axios.post(_this.requestUrl + '/dyicform/result', saveFrom, {
                    headers: {
                        Authorization: _this.token
                    }
                }).then(function (response) {
                    if (response.data.code === 101) {
                        _this.$toast.success('提交成功');

                        var orgLocalUrl = _this.replaceParamVal(document.URL, 'orglocal', 1);
                        var pagetypeUrl = _this.replaceParamVal(orgLocalUrl, 'pagetype', 3);
                        var questiontypeUrl = _this.replaceParamVal(pagetypeUrl, 'questiontype', _this.questionType);
                        // var url = _this.replaceParamVal(questiontypeUrl, 'create_date', _this.getCurrentDate());
                        var url = _this.replaceParamVal(questiontypeUrl, 'id', response.data.data.id);
                        window.location.href = url
                    }
                })
            },

            loadHisList() {
                var _this = this
                _this.$toast.loading({
                    message: '加载中...',
                    forbidClick: true
                });
                axios.post(_this.requestUrl + '/dyicform/info', {check_type: '2'}, {
                    headers: {
                        Authorization: _this.token
                    }
                }).then(function (response) {
                    _this.$toast.clear();
                    _this.hisList = response.data.data;
                    _this.finished = true
                    _this.refreshing = false
                })
            },
            loadHistoryFormData() {
                var _this = this
                _this.$toast.loading({
                    message: '加载中...',
                    forbidClick: true
                });
                axios.post(_this.requestUrl + '/dyicform/detail', {
                    id: _this.id,
                    // check_type: '2',
                    check_code: _this.questionType,
                    // create_date: decodeURIComponent( _this.create_date)
                }, {
                    headers: {
                        Authorization: _this.token
                    }
                }).then(function (response) {
                    _this.$toast.clear();

                    var data = response.data.data;

                    // 组装健康指标介绍
                    var option = _this.dealChartData(data.list);
                    _this.aboutData = data.check_desc;

                    setTimeout(function () {
                        _this.initLineChart(option)
                    }, 100)
                })
            },
            dealChartData(data) {

                data = data.reverse()
                var xAxisArr = [];
                var xlineNames = [];
                var seriesArr = [];
                var tableArr = [];

                for (let i = 0; i < data.length; i++) {
                    var item = data[i]

                    xAxisArr.push(this.dateFormat('YYYY-mm-dd', new Date(item.create_date)))
                    xlineNames.push(item.check_name)
                }

                var xhash = new Set(xAxisArr);
                var nhash = new Set(xlineNames);
                xAxisArr = [...xhash]
                xlineNames = [...nhash]

                this.create_date = xAxisArr[xAxisArr.length - 1];
                if (xAxisArr.length > 1) {
                    this.lastDate = xAxisArr[xAxisArr.length - 2];
                }

                for (let i = 0; i < xlineNames.length; i++) {

                    var line = [];
                    var x = xlineNames[i]
                    var about = {
                        check_name: x,
                        check_desc: ''
                    }
                    var contrast = {
                        check_name: x,
                        current_check_value: '-',
                        last_check_value: '-'
                    }

                    data.map(n => {
                        if (n.check_name == x) {
                            about.check_desc = n.check_desc;
                            line.push(parseFloat(n.check_value))
                        }
                    })

                    // // 组装健康指标介绍
                    // this.aboutData.push(about);
                    // 组装图表line数据
                    seriesArr.push({
                        name: x,
                        type: 'line',
                        data: line
                    })
                    // 组装对照表数据
                    var len = line.length;
                    if (len > 1) {
                        contrast.current_check_value = line[len - 1]
                        contrast.last_check_value = line[len - 2]
                    } else if (line.length === 1) {
                        contrast.current_check_value = line[len - 1]
                    }
                    this.tableData.push(contrast)
                }

                return {
                    xAxis: xAxisArr,
                    names: xlineNames,
                    series: seriesArr
                }
            },
            onLoad() {
                this.loadHisList()
            },
            onRefresh() {
                // 清空列表数据
                this.finished = false;

                // 重新加载数据
                // 将 loading 设置为 true，表示处于加载状态
                this.loading = true;
                this.onLoad();
            },
            cellClick(i) {
                var orgLocalUrl = this.replaceParamVal(document.URL, 'orglocal', 2);
                var pagetypeUrl = this.replaceParamVal(orgLocalUrl, 'pagetype', 3);
                var questiontypeUrl = this.replaceParamVal(pagetypeUrl, 'questiontype', i.check_code);
                // var url = this.replaceParamVal(questiontypeUrl, 'create_date', i.create_date);
                var url = this.replaceParamVal(questiontypeUrl, 'id', i.id);
                window.location.href = url
            },
            initLineChart(opt) {
                var _this = this
                _this.lineChart = echarts.init(document.getElementById('eChart'));

                var option = {
                    title: {
                        text: '健康指数对比',
                        textStyle: {//主标题文本样式{"fontSize": 18,"fontWeight": "bolder","color": "#333"}
                            fontSize: 16,
                        },
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        x: 'center',      //可设定图例在左、右、居中
                        y: 'bottom',     //可设定图例在上、下、居中
                        padding: [0, 0, 0, 0],   //可设定图例[距上方距离，距右方距离，距下方距离，距左方距离]
                        data: opt.names
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        top: '12%',
                        bottom: '15%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            show: true,
                            textStyle: {
                                fontSize: 14
                            }
                        },
                        data: opt.xAxis
                    },
                    yAxis: {
                        type: 'value',
                        splitNumber: 4,
                        splitLine: {
                            lineStyle: {
                                type: 'dashed',
                                color: '#DDD'
                            }
                        },
                        axisLine: {
                            show: false,
                            lineStyle: {
                                color: '#333'
                            }
                        },
                        nameTextStyle: {
                            color: '#999'
                        },
                        splitArea: {
                            show: false
                        }
                    },
                    series: opt.series
                };

                _this.lineChart.setOption(option, true)
            },

            onClickLeft() {
                if (this.orgLocal == 2) {
                    window.history.go(-1)
                } else {
                   // pensionPlatform.cancel();
                   window.webkit.messageHandlers.BackVC.postMessage(null);
                }
            },
            onClickRight() {
                var pagetypeUrl = this.replaceParamVal(document.URL, 'pagetype', 2);
                window.location.href = pagetypeUrl
            },

            getQueryVariable(variable) {
                var query = window.location.search.substring(1);
                var vars = query.split('&');
                for (var i = 0; i < vars.length; i++) {
                    var pair = vars[i].split('=');
                    if (pair[0] == variable) {
                        return pair[1];
                    }
                }
                return (false);
            },
            // 替换指定传入参数的值,paramName为参数,replaceWith为新值
            replaceParamVal(oUrl, paramName, replaceWith) {
                // var oUrl = this.location.href.toString();
                var reg = eval('/(' + paramName + '=)([^&]*)/gi');
                var flag = reg.test(oUrl);
                var nUrl = oUrl;
                if (flag) {
                    nUrl = oUrl.replace(reg, paramName + '=' + replaceWith);
                } else {
                    nUrl = oUrl + '&' + paramName + '=' + replaceWith;
                }
                return nUrl
            },
            getCurrentDate() {
                var date = new Date();
                var Y = date.getFullYear()
                var M = date.getMonth() + 1
                var D = date.getDate()
                return Y + '-' + M + '-' + D;
            },
            dateFormat(fmt, date) {
                let ret;
                const opt = {
                    'Y+': date.getFullYear().toString(),        // 年
                    'm+': (date.getMonth() + 1).toString(),     // 月
                    'd+': date.getDate().toString(),            // 日
                    'H+': date.getHours().toString(),           // 时
                    'M+': date.getMinutes().toString(),         // 分
                    'S+': date.getSeconds().toString()          // 秒
                    // 有其他格式化字符需求可以继续添加，必须转化成字符串
                };
                for (let k in opt) {
                    ret = new RegExp('(' + k + ')').exec(fmt);
                    if (ret) {
                        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
                    }
                }
                return fmt;
            },
        }
    });
</script>
</html>
